<template>
  <div class="admin-add-pet">
    <div class="container">
      <div class="back-link mb-3">
        <router-link to="/admin/pets">
          <i class="el-icon-arrow-left"></i> 返回宠物列表
        </router-link>
      </div>
      
      <h1 class="page-title">添加宠物</h1>
      
      <el-card class="pet-form-card" v-loading="loading">
        <el-form 
          ref="petForm" 
          :model="petData" 
          :rules="rules" 
          label-position="top"
          @submit.prevent="submitForm"
        >
          <el-row :gutter="20">
            <el-col :md="12" :sm="24">
              <el-form-item label="宠物名称" prop="name">
                <el-input v-model="petData.name" placeholder="请输入宠物名称" />
              </el-form-item>
            </el-col>
            
            <el-col :md="12" :sm="24">
              <el-form-item label="类别" prop="category_id">
                <el-select v-model="petData.category_id" placeholder="请选择宠物类别" style="width: 100%">
                  <el-option 
                    v-for="category in categories" 
                    :key="category.id" 
                    :label="category.name" 
                    :value="category.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :md="6" :sm="12" :xs="24">
              <el-form-item label="性别" prop="gender">
                <el-select v-model="petData.gender" placeholder="请选择性别" style="width: 100%">
                  <el-option label="公" value="male" />
                  <el-option label="母" value="female" />
                  <el-option label="未知" value="unknown" />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :md="6" :sm="12" :xs="24">
              <el-form-item label="年龄" prop="age">
                <el-input-number v-model="petData.age" :precision="1" :step="0.5" :min="0" :max="30" style="width: 100%" />
              </el-form-item>
            </el-col>
            
            <el-col :md="6" :sm="12" :xs="24">
              <el-form-item label="品种" prop="breed">
                <el-input v-model="petData.breed" placeholder="请输入品种" />
              </el-form-item>
            </el-col>
            
            <el-col :md="6" :sm="12" :xs="24">
              <el-form-item label="体型" prop="size">
                <el-select v-model="petData.size" placeholder="请选择体型" style="width: 100%">
                  <el-option label="小型" value="small" />
                  <el-option label="中型" value="medium" />
                  <el-option label="大型" value="large" />
                  <el-option label="超大型" value="extra large" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="是否已被领养">
                <el-switch v-model="petData.is_adopted" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="描述" prop="description">
            <el-input 
              type="textarea" 
              v-model="petData.description" 
              placeholder="请输入宠物的详细介绍" 
              :rows="5" 
            />
          </el-form-item>
          
          <el-form-item label="健康状况" prop="health_status">
            <el-input 
              type="textarea" 
              v-model="petData.health_status" 
              placeholder="请输入宠物的健康状况" 
              :rows="3" 
            />
          </el-form-item>
          
          <el-form-item label="行为习性" prop="behavior">
            <el-input 
              type="textarea" 
              v-model="petData.behavior" 
              placeholder="请输入宠物的行为习性" 
              :rows="3" 
            />
          </el-form-item>
          
          <el-form-item label="宠物照片" prop="image">
            <el-upload
              class="pet-image-uploader"
              action="#"
              :http-request="uploadImage"
              :show-file-list="false"
              :before-upload="beforeImageUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="pet-image" />
              <i v-else class="el-icon-plus pet-image-uploader-icon"></i>
              <div class="el-upload__tip">请上传宠物照片，只能上传 jpg/png 文件，且不超过 5MB</div>
            </el-upload>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="submitForm" :loading="submitting">添加宠物</el-button>
            <el-button @click="$router.push('/admin/pets')">取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useStore } from 'vuex';
import axios from 'axios';

export default {
  name: 'AdminAddPet',
  setup() {
    const store = useStore();
    const router = useRouter();
    const petForm = ref(null);
    const loading = ref(false);
    const submitting = ref(false);
    const imageUrl = ref('');
    const imageFile = ref(null);
    
    const API_URL = process.env.VUE_APP_API_URL || 'http://localhost:3000/api';
    
    // 表单数据
    const petData = reactive({
      name: '',
      category_id: '',
      breed: '',
      age: 0,
      gender: 'unknown',
      size: 'medium',
      description: '',
      health_status: '',
      behavior: '',
      is_adopted: 0,
      image_url: ''
    });
    
    // 分类数据
    const categories = ref([]);
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入宠物名称', trigger: 'blur' },
        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      category_id: [
        { required: true, message: '请选择宠物类别', trigger: 'change' }
      ],
      gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ],
      size: [
        { required: true, message: '请选择体型', trigger: 'change' }
      ],
      age: [
        { required: true, message: '请输入宠物年龄', trigger: 'blur' }
      ]
    };
    
    // 获取认证头
    const getAuthHeaders = () => {
      const token = store.getters['auth/token'];
      if (!token) {
        throw new Error('未找到认证令牌，请重新登录');
      }
      
      return {
        'Authorization': `Bearer ${token}`,
        'x-auth-token': token,
        'Content-Type': 'multipart/form-data'
      };
    };
    
    // 加载分类数据
    const loadCategories = async () => {
      loading.value = true;
      try {
        const token = store.getters['auth/token'];
        if (!token) {
          ElMessage.error('未登录或会话已过期，请重新登录');
          router.push('/login');
          return;
        }
        
        const response = await axios.get(`${API_URL}/pets/categories`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'x-auth-token': token
          }
        });
        categories.value = response.data;
      } catch (error) {
        ElMessage.error('加载分类数据失败');
        console.error(error);
      } finally {
        loading.value = false;
      }
    };
    
    // 图片上传前的验证
    const beforeImageUpload = (file) => {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 5;
      
      if (!isJPG && !isPNG) {
        ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!');
        return false;
      }
      
      if (!isLt5M) {
        ElMessage.error('上传头像图片大小不能超过 5MB!');
        return false;
      }
      
      imageFile.value = file;
      return true;
    };
    
    // 自定义上传图片方法
    const uploadImage = (options) => {
      const file = options.file;
      imageFile.value = file;
      
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        imageUrl.value = reader.result;
        // 注意：这里只是预览，实际的 image_url 是由服务器处理后返回的
      };
    };
    
    // 提交表单
    const submitForm = async () => {
      if (!petForm.value) return;
      
      try {
        await petForm.value.validate();
        
        if (!imageFile.value) {
          ElMessage.warning('请上传宠物照片');
          return;
        }
        
        // 检查登录状态
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未登录或会话已过期，请重新登录');
          router.push('/login');
          return;
        }
        
        submitting.value = true;
        
        // 创建表单数据
        const formData = new FormData();
        formData.append('image', imageFile.value);
        
        // 确保age是数字类型
        if (petData.age !== null && petData.age !== undefined) {
          petData.age = Number(petData.age);
        } else {
          petData.age = 0; // 默认值
        }
        
        // 确保category_id是整数
        if (petData.category_id) {
          petData.category_id = Number(petData.category_id);
        }
        
        // 添加符合数据库模型的字段到表单数据
        const fieldsToSubmit = [
          'name', 
          'category_id', 
          'breed', 
          'age', 
          'gender', 
          'size', 
          'description', 
          'health_status', 
          'behavior', 
          'is_adopted'
        ];
        
        // 显示提交的数据，便于调试
        console.log('提交前的宠物数据:', petData);
        
        fieldsToSubmit.forEach(key => {
          if (petData[key] !== undefined && petData[key] !== null) {
            formData.append(key, petData[key]);
          }
        });
        
        // 检查并打印表单数据
        for (let [key, value] of formData.entries()) {
          console.log(`表单字段 ${key}:`, value);
        }
        
        // 打印令牌状态
        console.log('发送请求前的令牌状态:', !!token);
        
        try {
          // 发送请求，确保包含正确的认证头
          const headers = {
            'Authorization': `Bearer ${token}`,
            'x-auth-token': token,
            'Content-Type': 'multipart/form-data'
          };
          
          console.log('使用的请求头:', headers);
          
          const response = await axios.post(`${API_URL}/pets`, formData, {
            headers: headers
        });
        
        ElMessage.success('宠物添加成功');
        router.push('/admin/pets');
        } catch (requestError) {
          console.error('发送请求失败:', requestError);
          
          if (requestError.response?.status === 401) {
            ElMessage.error('认证失败，请重新登录');
            router.push('/login');
          } else {
            ElMessage.error(`添加失败: ${requestError.message}`);
          }
        }
      } catch (error) {
        console.error('添加宠物失败:', error);
        const errorMessage = error.response?.data?.message || '添加宠物失败';
        
        // 处理认证错误
        if (error.response?.status === 401 || errorMessage.includes('令牌') || errorMessage.includes('token')) {
          ElMessage.error('认证失败，请重新登录');
          router.push('/login');
        } else {
        ElMessage.error(errorMessage);
        }
      } finally {
        submitting.value = false;
      }
    };
    
    // 组件挂载时加载数据
    onMounted(() => {
      loadCategories();
    });
    
    return {
      petForm,
      petData,
      categories,
      rules,
      loading,
      submitting,
      imageUrl,
      imageFile,
      beforeImageUpload,
      uploadImage,
      submitForm
    };
  }
}
</script>

<style lang="scss" scoped>
@use "sass:color";

.admin-add-pet {
  min-height: calc(100vh - 200px);
  padding: 40px 0;
}

.back-link {
  margin-bottom: 20px;
  
  a {
    color: var(--primary-color);
    display: inline-flex;
    align-items: center;
    
    i {
      margin-right: 5px;
    }
    
    &:hover {
      color: color.adjust(#42b983, $lightness: -10%);
    }
  }
}

.pet-form-card {
  margin-bottom: 40px;
}

.pet-image-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
    
    &:hover {
      border-color: var(--primary-color);
    }
  }
  
  .pet-image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
  }
  
  .pet-image {
    width: 200px;
    height: 200px;
    display: block;
    object-fit: cover;
  }
}

.mb-3 {
  margin-bottom: 15px;
}

@media (max-width: 768px) {
  .pet-image-uploader {
    .pet-image-uploader-icon,
    .pet-image {
      width: 100%;
    }
  }
}
</style> 